package reptile

import (
	"os"
	"os/exec"
	"robot/study/LiveRobot/define"
	"robot/study/LiveRobot/sdk/zlog"
	"strconv"
)

type Video struct {
	U *define.Message2
}

var videoTitle []string //视频标题
var videoUrl []string   //视频地址

//获取视频信息
func (vi *Video) Work() {
	spi := Spider{Str: `https://www.bilibili.com/v/popular/all?spm_id_from=333.851.b_7072696d61727950616765546162.3`}
	videoTitle, videoUrl = spi.Work()
	//视频是否已经下载过了
	go func() {
		for i := 0; i < len(videoTitle); i++ {
			t, err := PathExists("D:/robot/data/videos/" + videoTitle[i] + ".mp4")
			if err != nil {
				zlog.Error("检测videos失败")
			}
			if !t {
				if videoUrl != nil {
					//执行cmd命令，第一个参数是可执行文件you-get需要在网上下载python环境安装，第二个是保存文件，第三个是保存路径，第四个是视频资源地址，它暂定为全局对象
					cmd := exec.Command("C:/Users/admin/AppData/Local/Programs/Python/Python39/Scripts/you-get", "-o", "D:/robot/data/videos", videoUrl[i])
					// 执行命令，返回命令是否执行成功
					err := cmd.Run()

					if err != nil {
						// 命令执行失败
						panic(err)
					}
				}
			}
		}
		var ss string
		for i := 0; i < len(videoTitle); i++ {
			ss = ss + strconv.Itoa(i+1) + "." + videoTitle[i] + "\n"
		}
		if videoTitle != nil {
			msg := &define.Msg{
				Msg_type: vi.U.MessageType,
				Number:   int(vi.U.GroupId),
				Msg:      "已缓存视频：\n" + ss + "请@我回复视频+数字，观看",
			}
			Sendmsg(msg)
		}
	}()
	if videoTitle != nil {
		msg := &define.Msg{
			Msg_type: vi.U.MessageType,
			Number:   int(vi.U.GroupId),
			Msg:      "正在缓存",
		}
		Sendmsg(msg)
	}
}

//SendVideo 发送视频
func SendVideo(u *define.Message2) {
	x := u.RawMessage[len(u.RawMessage)-1] - 48
	if x > 3 {
		return
	}
	if videoTitle != nil {
		video := "[CQ:video,file=file:///D:/robot/data/videos/" + videoTitle[x-1] + ".mp4]"
		msg := &define.Msg{
			Msg_type: u.MessageType,
			Number:   int(u.GroupId),
			Msg:      video,
		}
		Sendmsg(msg)
	}
}

//PathExists 检测文件是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
